﻿
package system.base;

import system.data.UserMenuinfoPageData;
import system.data.UserPageData;

import com.apep.permission.CookieUtils;
import com.apep.permission.PermissionFilter;

import framework.core.Config;
import framework.core.ConstDefine;
import framework.core.DBConnection;
import framework.core.IHandler;
import framework.core.ILoginContext;
import framework.core.Logger;
import framework.core.ObjectList;
import framework.core.PageData;
import framework.core.SearchEvent;
import framework.core.SrvContext;
/*
	Author    :justin
	CreateTime:2008-01-03 16:27:25
 */
public class UserSrv extends IHandler
{

	public UserSrv()
	{
		super();
	}
	private void deleteUser(DBConnection con,SrvContext context) throws Exception
	{
		String[] ids = context.getParameterValues("ids");
		User obj = null;
		for(int i=0;i<ids.length;i++)
		{
			obj = User.fetch(con,ids[i]);
			if(obj!=null) {
				obj.delete(con);
			}
		}
	}
	private void saveUser(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		String id = context.getString("Id",null);
		User obj;
		if(id==null||id.equals(""))   //add
		{
			obj = User.fetch();
		}
		else                     //update
		{
			obj = User.fetch(con,id);
		}
		UserPageData data = (UserPageData)PageData.fromForm(context,UserPageData.class);

		Warehouse tmpW = Warehouse.fetchByCode(con,data.getWarehouseCode());
		if (tmpW!=null){
			data.setWarehouseName(tmpW.getName());
		}

		context.setValue("UserPageData",data);
		obj.fill(data);
		obj.save(con);
	}
	private void listUser(DBConnection con,SrvContext context,String path,ILoginContext loginContext) throws Exception
	{
		UserSearchEvent event = (UserSearchEvent)SearchEvent.fromForm(context,UserSearchEvent.class);

		//仓库条件加入
		if (event.getWarehouseCode()==null||event.getWarehouseCode().equals("")){
			event.setWarehouseCode(ConstDefine.getWildCard(loginContext.getLoginWarehouseCode())+"%");
		}

		context.setSessionValue("UserSearchEvent",event);
		context.setNextUrl(path+"UserList.jsp");
	}
	private void backUser(DBConnection con,SrvContext context,String path) throws Exception
	{
		context.setNextUrl(path+"UserList.jsp");
	}

	public void doAction(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		String action_code = context.getActionCode();
		String path = "/system/base/";

		if(action_code.equalsIgnoreCase("listUser"))
		{
			listUser(con,context,path,loginContext);
			return;
		}
		if(action_code.equalsIgnoreCase("viewUser"))
		{
			String id = context.getString("Id",null);
			User obj = User.fetch(con,id);
			context.setValue("User",obj);
			context.setNextUrl(path+"UserView.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("deleteUser"))
		{
			context.setErrorUrl(path+"UserList.jsp");
			deleteUser(con,context);
			backUser(con,context,path);
			return;
		}

		if(action_code.equalsIgnoreCase("toAddUser"))
		{
			User obj = User.fetch();
			UserPageData data = (UserPageData)PageData.fromTable(obj,UserPageData.class);
			context.setValue("UserPageData",data);
			context.setNextUrl(path+"UserEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("toUpdateUser"))
		{
			String id = context.getString("Id",null);
			User obj = User.fetch(con,id);
			UserPageData data = (UserPageData)PageData.fromTable(obj,UserPageData.class);
			context.setValue("UserPageData",data);
			context.setNextUrl(path+"UserEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("toCopyUser"))
		{
			String id = context.getString("Id",null);
			User obj = User.copy(User.fetch(con,id));
			UserPageData data = (UserPageData)PageData.fromTable(obj,UserPageData.class);
			context.setValue("UserPageData",data);
			context.setNextUrl(path+"UserEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("saveUser"))
		{
			context.setErrorUrl(path+"UserEdit.jsp");
			saveUser(con,context,loginContext);
			backUser(con,context,path);
			return;
		}
		if(action_code.equalsIgnoreCase("saveAndNewUser"))
		{
			context.setErrorUrl(path+"UserEdit.jsp");
			saveUser(con,context,loginContext);
			User obj = User.fetch();
			UserPageData data = (UserPageData)PageData.fromTable(obj,UserPageData.class);
			context.setValue("UserPageData",data);
			context.setNextUrl(path+"UserEdit.jsp");
			return;
		}
		//chengbiao.he start
		if(action_code.equalsIgnoreCase("saveAndNewConsumer"))
		{
			context.setErrorUrl(path+"ConsumerEdit.jsp");
			saveUser(con,context,loginContext);
			User obj = User.fetch();
			UserPageData data = (UserPageData)PageData.fromTable(obj,UserPageData.class);
			context.setValue("UserPageData",data);
			context.setNextUrl(path+"ConsumerEdit.jsp");
			context.setErrorMsg("用户信息设置成功!");
			return;
		}


		//chengbiao.he end

		if(action_code.equalsIgnoreCase("backListUser"))
		{
			backUser(con,context,path);
			return;
		}

		//add by justin start

		//login
		if (action_code.equalsIgnoreCase("login"))
		{
			login(con, context, path);
			return;
		}
		//视图切换经典视图
		if(action_code.equalsIgnoreCase("sutra")){
			context.setNextUrl("/system/index.jsp");
			return;
		}
		//简洁视图
		if(action_code.equalsIgnoreCase("simpview")){
			context.setNextUrl("/system/indexterse.jsp");
			return;
		}

		//add by justin end

		//add by wing start

		//到用户权限设置页面
		if(action_code.equalsIgnoreCase("toUserFuncSet"))
		{
			String userId = context.getString("userId",null);
			if(userId != null){
				User user = User.fetch(con,userId);
				context.setSessionValue("UserDetail",user);

				UserMenuinfoSearchEvent userMenuinfoevent = new UserMenuinfoSearchEvent();
				userMenuinfoevent.setUserId(userId);
				userMenuinfoevent.setPageNum(1);
				userMenuinfoevent.setPageSize(ConstDefine.INT_MAX);
				ObjectList userMenuinfoList = UserMenuinfo.fetch().search(con, userMenuinfoevent);
				context.setSessionValue("UserMenuinfoList", userMenuinfoList);
			}
			MenuInfoSearchEvent menuInfoevent = new MenuInfoSearchEvent();
			menuInfoevent.setParentCode(MenuInfo.PARENT_CODE_TOP_INT);
			menuInfoevent.setPageNum(1);
			menuInfoevent.setPageSize(ConstDefine.INT_MAX);
			ObjectList menuInfoHeadList = MenuInfo.fetch().search(con,menuInfoevent);
			context.setSessionValue("MenuInfoHeadList", menuInfoHeadList);

			context.setNextUrl(path+"UserFuncSet.jsp");
			return;
		}

		//用户权限修改
		if(action_code.equalsIgnoreCase("saveUserFuncSet"))
		{
			context.setErrorUrl(path+"UserFuncSet.jsp");
			saveUserFunc(con,context,loginContext);
			backUser(con,context,path);
			return;
		}
		//add by wing end

		// add by Jackey start
		// 登出
		if (action_code.equalsIgnoreCase("logout"))
		{
			logout(con, context, loginContext);
			return;
		}

		// add by Jackey end

		//到用户设置

		if (action_code.equalsIgnoreCase("toUpdateUserPwd"))
		{
			/*
            User user = new User();




          UserPageData data = (UserPageData)PageData.fromForm(context,UserPageData.class);
           String id = context.getString("Id",null);
           User obj;
           obj = User.fetch(con, id);
            if(!id.equals(""))   //add
            {

                obj.setCode(loginContext.getLoginUserName());
                obj.setWarehouseName(loginContext.getLoginWarehouseName());

            }
			 */


			context.setNextUrl(path+"ConsumerEdit.jsp");
			return;
		}


		Logger.throwException("UserSrv","unknown action_code="+action_code);
	}

	//	add by justin start
	private boolean login(DBConnection con, SrvContext context, String path)
	throws Exception
	{
		context.setErrorUrl("/system/login.jsp");

		String userCode = context.getString("Code");
		String password = context.getString("Password");


		if (system.LoginContext.login(con, context, userCode, password, Config.isDebug()))
		{
			//用户是否有权限进行视图切换
			//		    if(LoginContext.get(context).isView()){
			//		        context.setNextUrl("/system/indexterse.jsp");
			//            }else{
			//                context.setNextUrl("/system/index.jsp");
			//            }
			context.m_res.setHeader("location", context.m_req.getSession().getId());
			context.setNextUrl("/system/index.jsp");


			CookieUtils.setValue(context.m_req, context.m_res, PermissionFilter.COOKIE_USER_CODE_NAME, userCode, PermissionFilter.EIGHT_HOURS);
			CookieUtils.setValue(context.m_req, context.m_res, PermissionFilter.COOKIE_PASSWORD_NAME, password, PermissionFilter.EIGHT_HOURS);

			return true;
		}else{
			context.setErrorMsg("登录失败,用户名或密码错误!");
			context.setValue("NextUrl", "/system/Login.jsp");
			context.setNextUrl("/system/login.jsp");
			return false;
		}
	}
	//	add by justin end

	//add by wing start

	//用户权限保存
	private void saveUserFunc(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		String userId = context.getString("userId",null);
		UserMenuinfoSearchEvent userMenuinfoevent = new UserMenuinfoSearchEvent();
		userMenuinfoevent.setUserId(userId);
		UserMenuinfo userMenuinfo = UserMenuinfo.fetch(con, userMenuinfoevent.toConditions());
		if(userMenuinfo!=null) {
			userMenuinfo.deleteByUserId(con, userId);
		}

		String []menuId = context.getParameterValues("MenuId");
		/** benny start :当权限被全部取消时,需判断权限数组是否为空 2008-03-13-18-53   */
		if(menuId == null || menuId.length <= 0) {
			return;
		}
		/***/
		for(int i=0;i<menuId.length;i++){
			UserMenuinfo obj = UserMenuinfo.fetch();
			UserMenuinfoPageData data = (UserMenuinfoPageData)PageData.fromForm(context,UserMenuinfoPageData.class);
			data.setUserId(userId);

			MenuInfo menuInfo = MenuInfo.fetch(con,menuId[i]);
			if (menuInfo!=null){
				data.setMenuId(menuId[i]);
				data.setMenuCode(menuInfo.getMenuCode()+"");
			}
			obj.fill(data);
			obj.save(con);
		}
	}
	//add by wing end

	// add by Jackey start
	private void logout(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		system.LoginContext.loginOut(context);
		context.setNextUrl("/system/login.jsp");
	}
	// add by Jackey end


}
